package com.itheima.service.impl;

import com.itheima.dao.ModuleDao;
import com.itheima.domain.Module;
import com.itheima.service.ModuleService;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.UUID;

public class ModuleServiceImpl implements ModuleService {
    @Override
    public List<Module> findAll() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        ModuleDao mapper = sqlSession.getMapper(ModuleDao.class);
        List<Module> modulesOne = mapper.findModuleOne();
        for (Module module : modulesOne) {
            String parentId = module.getModuleId();
            List<Module> modulesTwo = mapper.findModuleTwo(parentId);
           module.setChildren(modulesTwo);
        }
        sqlSession.close();
        return modulesOne;
    }

    @Override
    public void delete(String id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        ModuleDao mapper = sqlSession.getMapper(ModuleDao.class);
        mapper.delete(id);
        sqlSession.close();
    }

    @Override
    public void update(Module module) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        ModuleDao mapper = sqlSession.getMapper(ModuleDao.class);
        mapper.update(module);
        sqlSession.close();
    }

    @Override
    public void add(Module module) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        ModuleDao mapper = sqlSession.getMapper(ModuleDao.class);
        String id = UUID.randomUUID().toString();
        module.setModuleId(id);
        mapper.add(module);
        sqlSession.close();
    }
}
